package wn.lizzy.liums.config.datasource;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 多数据源 主数据源配置
 * RepositoryPrimaryConfig.java
 * @author cuilijian  2017年3月20日--下午4:48:17
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
		entityManagerFactoryRef="entityManagerFactoryPrimary",
		transactionManagerRef="transactionManagerPrimary",
		basePackages= { "wn.lizzy.liums.system.basic" })//设置dao（repo）所在位置
	public class RepositoryPrimaryConfig {
	 @Autowired  
	    private JpaProperties jpaProperties;  
	  
	    @Autowired  
	    @Qualifier("PrimaryDataSource")  
	    private DataSource PrimaryDataSource;  
	  
	    @Bean(name = "entityManagerPrimary")  
	    @Primary  
	    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {  
	        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();  
	    }  
	  
	    @Bean(name = "entityManagerFactoryPrimary")  
	    @Primary  
	    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {  
	        return builder  
	                .dataSource(new LazyConnectionDataSourceProxy(PrimaryDataSource))  
	                .properties(getVendorProperties(PrimaryDataSource))  
	                .packages("wn.lizzy.liums.system.basic.entity") //设置实体类所在位置  
	                .persistenceUnit("primaryPersistenceUnit")  
	                .build();  
	    }  
	  
	    private Map<String, String> getVendorProperties(DataSource dataSource) {  
	        return jpaProperties.getHibernateProperties(dataSource);  
	    }  
	  
	    @Bean(name = "transactionManagerPrimary")  
	    @Primary  
	    PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {  
	        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());  
	    }  
	}
